package com.example.myfirst.controller;

import com.example.myfirst.dto.UserDto;
import com.example.myfirst.entity.User;
import com.example.myfirst.service.UserService;
import com.example.myfirst.vo.ResultVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin // 解决前后跨域
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation("查询所有用户信息")
    @GetMapping
    private ResultVo<User> getAllUser() {
        List<User> userList = userService.queryAllUser();
        return new ResultVo<>(userList);
    }

    @ApiOperation("添加用户")
    @PostMapping("/register")
    private ResultVo addUser(@RequestBody User user) {
        boolean flag = userService.addUser(user);
        ResultVo vo = new ResultVo<>();
        if (flag) {
            vo.setMessage("注册成功");
            vo.setSuccess(true);
        } else {
            vo.setMessage("注册失败");
            vo.setSuccess(false);
        }
        vo.setCode(200);
        return vo;
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{id}")
    private ResultVo delUser(@PathVariable Integer id) {
        boolean flag = userService.delUserByID(id);
        ResultVo vo = new ResultVo<>();
        if (flag) {
            vo.setMessage("删除成功");
            vo.setSuccess(true);
        } else {
            vo.setMessage("删除失败");
            vo.setSuccess(false);
        }
        vo.setCode(200);
        return vo;
    }

    @ApiOperation("根据id查询用户")
    @GetMapping("/{id}")
    public ResultVo getUserById(@PathVariable Integer id) {
        List<User> users = userService.queryUserById(id);
        return new ResultVo(users);
    }

    @ApiOperation("根据id修改用户")
    @PutMapping("/{id}")
    public ResultVo updateUserById(@RequestBody User user,@PathVariable Integer id) {
        Boolean flag = userService.updateUserById(user, id);
        ResultVo vo = new ResultVo<>();
        if (flag) {
            vo.setMessage("修改用户成功");
            vo.setSuccess(true);
        } else {
            vo.setMessage("修改用户失败~");
            vo.setSuccess(false);
        }
        vo.setCode(200);
        return vo;
    }

    @ApiOperation("登录校验")
    @PostMapping("/login")
    public ResultVo userLogin(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        UserDto login = userService.login(username, password);
        if (login != null) {
            return new ResultVo("登录成功", true, login);
        } else {
            return new ResultVo("账号或密码错误", false);
        }
    }
}
